package com.stephen.demo.shiro.realms;

import com.stephen.demo.entity.Role;
import com.stephen.demo.entity.User;
import com.stephen.demo.service.UserService;
import com.stephen.demo.shiro.salt.MyByteSource;
import com.stephen.demo.utils.ApplicationContextUtil;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;

import java.util.Set;
import java.util.stream.Collectors;

/**
 * Created by stephen on 2021-04-05 12:15 .
 * Description: 自定义Realm
 */
public class CustomizeRealm extends AuthorizingRealm {

    // 授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        String username = (String) principals.getPrimaryPrincipal();
        // 获取角色信息
        UserService userService = (UserService) ApplicationContextUtil.getBean("userService");
        Set<Role> roles = userService.getRoleByUsername(username);
        if (!CollectionUtils.isEmpty(roles)) {
            // 给角色赋值
            SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
            // 赋予角色
            authorizationInfo.addRoles(roles.stream().map(e->e.getName()).collect(Collectors.toList()));
            roles.forEach(role -> {
                Set<String> perms = userService.getPermsByRoleId(role.getId());
                if (!CollectionUtils.isEmpty(perms)) {
                    // 赋予权限
                    authorizationInfo.addStringPermissions(perms);
                }
            });
            return authorizationInfo;
        }
        return null;
    }

    // 认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        String principal = (String) token.getPrincipal();

        UserService userService = (UserService) ApplicationContextUtil.getBean("userService");
        User user = userService.findByUserName(principal);
        if (!ObjectUtils.isEmpty(user)) {
            return new SimpleAuthenticationInfo(principal,user.getPassword(),new MyByteSource(user.getSalt()),this.getName());
        }
        return null;
    }
}
